package org.example.web.global;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *全局过滤器设置编码格式
 */
public class EncodingFilter implements Filter {
    //模式编码为utf-8
    String encoding = "utf-8";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //获得初始化配置信息
        //没有初始化编码格式就设置为默认值，有就使用初始化的编码格式
        if(filterConfig.getInitParameter("encoding") != null){
            encoding = filterConfig.getInitParameter("encoding");
        }
    }
    //设置请求和响应的编码格式
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletRequest.setCharacterEncoding(encoding);
        httpServletResponse.setCharacterEncoding(encoding);
        chain.doFilter(httpServletRequest,httpServletResponse);
    }

    @Override
    public void destroy() {

    }
}
